package fr.zadoka.zadokadna;


import java.util.GregorianCalendar;

import fr.zadoka.zadokadna.Util.CalendarUtil;
import fr.zadoka.zadokadna.db.ZadokaDatabaseContract;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.content.CursorLoader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

public class FavoriteActivity extends ActionBarActivity 
							implements LoaderCallbacks<Cursor>,
							OnPageChangeListener
{

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		refreshCurrentImage();			
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return super.onPrepareOptionsMenu(menu);
	}

	private static final int FAVORITE_LOADER = 0;

	private static final String[] PROJECTION =
	    {
			//ZadokaDatabaseContract.ZadokaFavoriteContract._ID,
			ZadokaDatabaseContract.ZadokaFavoriteContract.ZADOKA_DNA_IMAGE_DATE
	    };

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
	 * derivative, which will keep every loaded fragment in memory. If this
	 * becomes too memory intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	FavoritePageAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;
	
	ZadokaFavorites zadokaFavorites;
	
	private ZadokaNavigationDrawer mNavigationDrawer;

	@Override
	public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle) {
		 /*
         * Takes action based on the ID of the Loader that's being created
         */
        switch (loaderID) {
            case FAVORITE_LOADER:
            // Returns a new CursorLoader
            return new CursorLoader(
                        this,                                     // Context
                        ZadokaDatabaseContract.ZadokaFavoriteContract.FAVORITE_TABLE_CONTENTURI,  // Table to query
                        PROJECTION,                                        // Projection to return
                        null,                                              // No selection clause
                        null,                                              // No selection arguments
                        ZadokaDatabaseContract.ZadokaFavoriteContract.ZADOKA_DNA_IMAGE_DATE + " DESC"                                              // Default sort order
            );
            default:
                // An invalid id was passed in
                return null;

        }	
    }

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		mSectionsPagerAdapter.swapCursor(cursor);
		refreshCurrentImage();
		
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		mSectionsPagerAdapter.swapCursor(null);		
	}

	// ActionBarActivity

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_favorite);
		
		ActionBar actionBar = getSupportActionBar();
		actionBar.setDisplayHomeAsUpEnabled(false);
		
		zadokaFavorites = new ZadokaFavorites(this);	

		mSectionsPagerAdapter = new FavoritePageAdapter(getSupportFragmentManager(), null);
		FavoriteFragment.mFavorites = zadokaFavorites;

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);
		mViewPager.setOnPageChangeListener(this);		
			
		
		mNavigationDrawer = new ZadokaNavigationDrawer(this);
		
		// Initializes the CursorLoader
		getSupportLoaderManager().initLoader(FAVORITE_LOADER, null, this);		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.favorite, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		
		if (mNavigationDrawer.onOptionsItemSelected(item)) {
	          return true;
	        }		
		
		int id = item.getItemId();
		
		if(id == R.id.action_favorite)
		{
		
			removeFromFavorite();
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	private void removeFromFavorite() {
		
		GregorianCalendar imageDate = mSectionsPagerAdapter.getItemDate(mViewPager.getCurrentItem());
		
		String where = ZadokaDatabaseContract.ZadokaFavoriteContract.ZADOKA_DNA_IMAGE_DATE + " = ?";
		String[] whereArgs = new String[]{CalendarUtil.GregorianCalendarToString(imageDate)};
		
		//delete the image from the favorite db
		getContentResolver().delete(ZadokaDatabaseContract.ZadokaFavoriteContract.FAVORITE_TABLE_CONTENTURI, 
									where , 
									whereArgs );
		
		//delete the image from the favorite file manager
		zadokaFavorites.deleteImage(imageDate);		
		StringBuilder sb = new StringBuilder();
		sb.append("Removed from the favorite");
		sb.append(" ");
		sb.append(CalendarUtil.GregorianCalendarToString(imageDate));
		int duration = Toast.LENGTH_LONG;

		Toast toast = Toast.makeText(getApplicationContext(), sb, duration);
		toast.show();	

		getSupportLoaderManager().restartLoader(FAVORITE_LOADER, null, this);
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int arg0) {	
		refreshCurrentImage();		
		supportInvalidateOptionsMenu();		
	}
	
	public void refreshCurrentImage()
	{
        //set the date in the action bar
		getSupportActionBar().setTitle(mSectionsPagerAdapter.getPageTitle(mViewPager.getCurrentItem()));	
	}
	

	public class FavoritePageAdapter extends FragmentStatePagerAdapter {

		private boolean hasFavorites() {
			 return (mCursor != null) && (mCursor.getCount() > 0);
		}
		
		@Override
		public CharSequence getPageTitle(int position) {
			if (!hasFavorites())
				return "";
			mCursor.moveToPosition(position);
			return mCursor.getString(0);
		}


		private Cursor mCursor; 
		
		public FavoritePageAdapter(FragmentManager fm, Cursor favoriteCursor) 
		{
			super(fm);
			mCursor = favoriteCursor;
			//mCursor.moveToFirst();
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a PlaceholderFragment (defined as a static inner class
			// below).
			if (!hasFavorites())
				return null;
			mCursor.moveToPosition(position);
			return FavoriteFragment.newInstance(mCursor.getString(0));
		}
		
		@Override
		public int getItemPosition(Object object) {
			// we always return POSITION_NONE to force the internal state refresh
			return POSITION_NONE;
		}
		

		@Override
		public int getCount() {
			return !hasFavorites() ? 0 : mCursor.getCount();
		}
		
		public GregorianCalendar getItemDate(int position)
		{
			if (!hasFavorites())
				return new GregorianCalendar();
			
			mCursor.moveToPosition(position);			
			String imageDateString = mCursor.getString(0);
			return CalendarUtil.StringToGregorianCalendar(imageDateString);
		}
		
 
		public void swapCursor(Cursor newCursor)
		{
			mCursor = newCursor;
			if(hasFavorites())
			{
				mCursor.moveToFirst();
				notifyDataSetChanged();
			}
		}
	}
	
	public static class FavoriteFragment extends Fragment {
		private static final String ARG_IMAGE_DATE = "image_date";
		private static ZadokaFavorites mFavorites;
		/**
		 * Returns a new instance of this fragment for the given section number.
		 */
		public static FavoriteFragment newInstance(String imageDate) {
			FavoriteFragment fragment = new FavoriteFragment();
			Bundle args = new Bundle();
			args.putString(ARG_IMAGE_DATE, imageDate);
			fragment.setArguments(args);
			return fragment;
		}

		public FavoriteFragment() {

		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_favorite,
					container, false);
			Bundle args = getArguments();
			
			Bitmap image = mFavorites.loadImage(CalendarUtil.StringToGregorianCalendar(args.getString(ARG_IMAGE_DATE)));
			if (image != null)
			{
				ImageView imageView = (ImageView) rootView.findViewById(R.id.favoriteImageView);		
				imageView.setImageBitmap(image);
			}
			
			return rootView;
		}

	}


}
